<template>
	<div>
		<div class="page has-navbar" v-nav="{title: pageTitle, showBackButton: true}">
			<div class="page-content padding-top">
				
				<scroller class="page-content cars-box" :on-refresh="onRefresh" :on-infinite="onInfinite"  ref="scroller">
					<car-search :params="params" @searchOptions="searchOptions" v-if="carStateJson.carOrderState != 1"  ></car-search>  
					<div class="filter-box weui-flex">
						<div class="weui-flex-item" @click="sort(true)">{{sortJson.sortTitle || '默认排序'}}</div>
						<div class="weui-flex-item" @click="filterBrand">{{((brandJson.brandName || '')+(brandJson.seriesName || '')+(brandJson.modelName || '')) || '品牌'}}</div>					
						<div class="weui-flex-item" @click="filterPrice">{{priceJson.title || '价格'}}</div>
						<div class="weui-flex-item" @click="shopStateShow=true">{{'状态'}}</div>
						<div class="weui-flex-item" @click="shopScreen=true">{{'筛选'}}</div>
					</div>
					<car-options :carsList="carsList" :status="true" :carStockState="carStateJson.carStockState" ></car-options>
				</scroller>
			</div>
		</div>
		<transition enter-active-class="animated fadeInRight" leave-active-class="animated fadeOutRight">
			<keep-alive>
				<screen-modal v-if="shopScreen" @cancel="cancel"></screen-modal>
			</keep-alive>
		</transition>
		<transition enter-active-class="animated fadeInRight" leave-active-class="animated fadeOutRight">
			<keep-alive>
				<screen-price v-if="showPrice" @cancel="cancel2"></screen-price>
			</keep-alive>
		</transition>
		<transition enter-active-class="animated fadeInRight" leave-active-class="animated fadeOutRight">
			<keep-alive>
				<screen-state v-if="shopStateShow" :params="carStateJson" @cancel="cancel3"></screen-state>
			</keep-alive>
		</transition>
	</div>
</template>
<script>
  import carSearch from 'src/assembly/searchModel.vue'
	import sortModalHang from '../sort/sort_hang.vue'
	import sortModalApply from '../sort/sort_apply.vue'
	import sortModalLibrary from '../sort/sort_library.vue'
	import sortModalReserve from '../sort/sort_reserve.vue'
	import sortModalSale from '../sort/sort_sale.vue'

	import screenState from 'src/assembly/screenState.vue'
	import screenModal from 'src/assembly/screenRange.vue'
	import screenPrice from 'src/assembly/screenPrice.vue'
	import brandModal from '../sort/brand.vue'
	import priceModal from '../sort/price.vue'
	import filterModal from '../sort/filter.vue'
	import { bus } from 'bus.js'
	export default {
		data() {
			return {
				carsList: [],
				pageTitle: '库存管理',
				pageNo: 0,
				pageNo2: 0,
				pageSize: 10,
				imgUrl: imgUrl,
				brandJson: {},
				sortJson: {},
				priceJson: {},
				carStateJson: {},
				shopScreen: false,
				rangeJson: {
					vage: {},
					mileage: {},
					oage: {},
				},
				brandModal: null,
				showPrice: false,
				shopId: sess.get('userSession').shopId,
				sortFn: '',
				shopStateShow: false,
				shopState: {},
				role:{
					shopId:'',
					marketId:'',
					userId:'',
				},
				carPosition: {},
				params:{
					carVin6: ''
				}
			}
		},
		components: {
			screenModal,
			screenPrice,
			screenState,
			carSearch,
		},
		mounted() {
			$modal.fromComponent(sortModalHang, {
				title: '排序',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.sortModalHang = modal;
			});
			$modal.fromComponent(sortModalApply, {
				title: '排序',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.sortModalApply = modal;
			});
			$modal.fromComponent(sortModalLibrary, {
				title: '排序',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.sortModalLibrary = modal;
			});
			$modal.fromComponent(sortModalReserve, {
				title: '排序',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.sortModalReserve = modal;
			});
			$modal.fromComponent(sortModalSale, {
				title: '排序',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.sortModalSale = modal;
			});

			$modal.fromComponent(brandModal, {
				title: '选择品牌',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.brandModal = modal;
			});

			$modal.fromComponent(priceModal, {
				title: '价格',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.priceModal = modal;
			});

			$modal.fromComponent(filterModal, {
				title: '筛选',
				theme: 'assertive',
				onHide: () => {
					// console.log();
				}
			}).then((modal) => {
				this.filterModal = modal;
			});

		},
		created() {
			this.carStateJson.carOrderState = this.$route.query.carOrderState;
			this.carStateJson.carStockState = this.$route.query.carStockState;
			this.pageTitle = this.$route.query.title;
			this.role.marketId = sess.get('userSession').marketId
			switch(this.$route.query.role){
				case 'ShopStaff':
					this.role.shopId = sess.get('userSession').shopId
					break
				case 'MarketStaff':
					this.role.userId = sess.get('userSession').userId
					break
				case 'MarketManager':
					this.role.marketId = sess.get('userSession').marketId
					break
				default:
					break
				
			}
			bus.$on('brandJson', (obj) => {
				this.brandJson = obj
				this.brandModal.hide();
				bus.$emit('hideAll');
				this.onRefresh();
			})
			bus.$off('sortJson')
			bus.$on('sortJson', (obj) => {
				this.sortJson = obj;
				this.sortModalSale.hide();
				this.sortModalReserve.hide();
				this.sortModalApply.hide();
				this.sortModalLibrary.hide();
				this.sortModalHang.hide();
				this.onRefresh();
			})
			bus.$on('priceJson', (obj) => {
				this.priceJson = obj;
				this.priceModal.hide();
				this.onRefresh();
			})
			this.sort(false)
		},
		destroyed() {
			if(this.sortModalSale)
				$modal.destroy(this.sortModalSale)
			if(this.sortModalReserve)
				$modal.destroy(this.sortModalReserve)
			if(this.sortModalLibrary)
				$modal.destroy(this.sortModalLibrary)
			if(this.sortModalApply)
				$modal.destroy(this.sortModalApply)
			if(this.sortModalHang)
				$modal.destroy(this.sortModalHang)
			if(this.brandModal)
				$modal.destroy(this.brandModal)
			if(this.priceModal)
				$modal.destroy(this.priceModal)
			if(this.filterModal)
				$modal.destroy(this.filterModal)
		},
		methods: {
			searchOptions (arr) {
        this.params.carVin6 = arr[0] ? arr[1] : ''
        this.onRefresh()
      },
			cancel(val) {
				this.shopScreen = false
				if(val) {
					if(val.shopId) {
						this.role.shopId = val.shopId
					}

					this.getParams(val)
				}
			},
			cancel2(val) {
				this.showPrice = false
				if(val) {
					this.priceJson.start = val.min
					this.priceJson.end = val.max
					this.onRefresh();
				}
			},
			cancel3(val) {
				this.shopStateShow = false
				if(val) {
					this.shopState = val
					this.onRefresh();
				}
			},
			sort(val) {
				switch(this.carStateJson.carStockState || this.carStateJson.carOrderState) {
					case '0':
						if(val) {
							this.sortModalHang.show()
						} else {
							this.sortJson = {
								sortName: 'CAR_CREATE_TIME',
								sortMode: 'DESC',
								sortTitle: '最近更新'
							}
						}
						break
					case '10':
						if(val) {
							this.sortModalApply.show()
						} else {
							this.sortJson = {
								sortName: 'CAR_STOCK_TIME',
								sortMode: 'DESC',
								sortTitle: '最近申请'
							}
						}
						break
					case '20':
						if(val) {
							this.sortModalLibrary.show()
						} else {
							this.sortJson = {
								sortName: 'CAR_STOCK_TIME',
								sortMode: 'DESC',
								sortTitle: '最近入库'
							}
						}
						break
					case '1':
						if(val) {
							this.sortModalReserve.show()
						} else {
							this.sortJson = {
								sortName: 'ORDER_CREATE_TIME',
								sortMode: 'DESC',
								sortTitle: '最新预定'
							}
						}
						break
					case '40':
						if(val) {
							this.sortModalSale.show()
						} else {
							this.sortJson = {
								sortName: 'SALE_CREATE_TIME',
								sortMode: 'DESC',
								sortTitle: '最近成交'
							}
						}
						break
					default:
						return false
						break
				}
			},
			filterBrand() {
				this.brandModal.show();
			},
			filterPrice() {
				this.showPrice = true
				//				this.priceModal.show();
			},
			filterBox() {
				this.filterModal.show();
			},
			getParams(obj) {
				this.rangeJson = obj;
				this.onRefresh();
			},
			onRefresh() {
				var _this = this;
				this.pageNo = 1;
				axios.get(baseUrl + '/controller/getCarList', {
						params: {
							carOrderState: this.carStateJson.carOrderState, //预订状态（1：已预订、0：未预订）
							carStockState: this.shopState.carStockState|| this.carStateJson.carStockState, //库存状态 0 初始化 10 入库中 20 入库 30 出库中 40 出库
							pageIndex: this.pageNo,
							pageSize: 10,
							marketId: this.role.marketId,
							shopId: this.role.shopId,
							brandId: this.brandJson.brandId,
							seriesId: this.brandJson.seriesId,
							modelId: this.brandJson.modelId,
							orderColunm: this.sortJson.sortName,
							orderMode: this.sortJson.sortMode,
							fromRetailPrice: this.priceJson.start,
							toRetailPrice: this.priceJson.end,
							fromCarAge: this.rangeJson.vage.min,
							toCarAge: this.rangeJson.vage.max,
							fromMileage: this.rangeJson.mileage.min,
							toMileage: this.rangeJson.mileage.max,
							fromCreateTime: this.rangeJson.oage.min,
							toCreateTime: this.rangeJson.oage.max,
							carOutColor: this.rangeJson.color,
							carTypeId: this.rangeJson.type,
							carEnviron: this.rangeJson.carEnviron,
							carSaleState: this.shopState.carSaleState,
							carDetectState: this.shopState.carDetectState,
							carBargainPriceState: this.shopState.carBargainPriceState,
							carPledgeState:this.shopState.carPledgeState,
							carAuthState:this.shopState.carAuthState,
							userId:this.role.userId,
							carVin6: this.params.carVin6,
						}
					})
					.then(function(res) {
						var resArr = res.data.result;
						if(resArr.length == 0) {
							_this.$refs.scroller.finishPullToRefresh(true);
							_this.carsList = resArr;
							return;
						}
						_this.carsList = resArr;
						setTimeout(() => {
							if(_this.$refs.scroller)
								_this.$refs.scroller.finishPullToRefresh()
						})
					})
			},

			onInfinite() {
				var _this = this;
				if (this.pageNo === 0 && this.$store.state.carObjState && typeof sess.get('carObjEdit').brandJson == typeof {}) {
					this.$store.commit('carObjStateChange', false)
					let carObj = sess.get('carObjEdit')
					sess.remove('carObjEdit')
					this.brandJson = carObj.brandJson
					this.sortJson = carObj.sortJson
					this.priceJson = carObj.priceJson
					this.marketJson = carObj.marketJson
					this.shopState = carObj.shopState
					this.carPosition = carObj.carPosition
					this.carPosition = carObj.carPosition
					this.pageSize = this.carPosition.pageNo * 10
					this.pageNo = 1
					this.pageNo2 = this.carPosition.pageNo
				} else {
					this.pageSize = 10
					this.pageNo += 1
				}
				axios.get(baseUrl + '/controller/getCarList', {
						params: {
							carOrderState: this.carStateJson.carOrderState, //预订状态（1：已预订、0：未预订）
							carStockState: this.shopState.carStockState|| this.carStateJson.carStockState, //库存状态 0 初始化 10 入库中 20 入库 30 出库中 40 出库
							pageIndex: this.pageNo,
							pageSize: this.pageSize,
							marketId: this.role.marketId,
							shopId: this.role.shopId,
							brandId: this.brandJson.brandId,
							seriesId: this.brandJson.seriesId,
							modelId: this.brandJson.modelId,
							orderColunm: this.sortJson.sortName,
							orderMode: this.sortJson.sortMode,
							fromRetailPrice: this.priceJson.start,
							toRetailPrice: this.priceJson.end,
							fromCarAge: this.rangeJson.vage.min,
							toCarAge: this.rangeJson.vage.max,
							fromMileage: this.rangeJson.mileage.min,
							toMileage: this.rangeJson.mileage.max,
							fromCreateTime: this.rangeJson.oage.min,
							toCreateTime: this.rangeJson.oage.max,
							carOutColor: this.rangeJson.color,
							carTypeId: this.rangeJson.type,
							carEnviron: this.rangeJson.carEnviron,
							carSaleState: this.shopState.carSaleState,
							carDetectState: this.shopState.carDetectState,
							carBargainPriceState: this.shopState.carBargainPriceState,
							carPledgeState: this.shopState.carPledgeState,
							carAuthState: this.shopState.carAuthState,
							userId:this.role.userId,
							carVin6: this.params.carVin6
						}
					})
					.then(function(res) {
						var resArr = res.data.result;
						if (_this.pageNo2>0) {
							_this.pageNo = _this.pageNo2
							_this.pageNo2 = 0
						}
						if(resArr.length == 0) {
							_this.$refs.scroller.finishInfinite(true);
							return;
						}

						for(var i = 0; i < resArr.length; i++) {
							_this.carsList.push(resArr[i])
						}
						setTimeout(() => {
							if(_this.$refs.scroller)
								_this.$refs.scroller.finishInfinite()
						}, 0)
						if (_this.carPosition.scrollerTop) {
							setTimeout(() => {
								_this.$refs['scroller'].scrollBy(0, _this.carPosition.scrollerTop, false)
								_this.carPosition = {}
							},20)
						}

					})
			},

		},
		beforeDestroy(){
			let obj = {
				pageNo: this.pageNo,
				scrollerTop: this.$refs['scroller'].getPosition().top
			}
			sess.set('carObjEdit', {
				carPosition: obj,
				brandJson: this.brandJson,
				sortJson: this.sortJson,
				priceJson: this.priceJson,
				rangeJson: this.rangeJson,
				shopState: this.shopState,
				marketJson: this.marketJson
			})
		}
	}
</script>
<style scoped>
	.filter-box {
		width: 100%;
		height: 40px;
		line-height: 40px;
		background-color: #fff;
	}
	
	.filter-box div {
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>